<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Configuration;
use app\Oss;
use think\facade\Filesystem;
use think\facade\Db;

class UploadService
{
    private $mallId;

    public function __construct()
    {
        global $user;
        $this->mallId = $user['mall_id'];
    }

    public function images($files)
    {
        $saveName = [];
        foreach ($files as $file) {
            foreach ($file as $v) {
                $path = "storage/" . Filesystem::disk('public')->putFile('madmin', $v);
                $oss = new Oss();
                $up = $oss->up($v->getPathname(), $path, $this->mallId);
                if (!is_null($up)) {
                    !empty($up) && @unlink($path);
                    $saveName[] = $up;
                } else {
                    $saveName[] = request()->server("REQUEST_SCHEME") . '://' .$_SERVER['HTTP_HOST'] . '/' . $path;
                }
            }
        }
        return [HTTP_SUCCESS, $saveName];
    }

    public function upBase64Img($string)
    {
        $path = "storage/" . $this->mallId . "/shop_admin";
        $res = base64_image_content($string, $path);
        $config = json_decode(Configuration::where('type', 'oss')->value('configuration'), true);
        //$saas_config = json_decode(Db::name('saas_configuration')->where('type', 'oss')->find()['configuration'], true);
        if ($config['oss_choice'] == 1) {
            $up = request()->server("REQUEST_SCHEME") . '://' .$_SERVER['HTTP_HOST'] . "/".$res;
        } else {
            $oss = new Oss();
            $up = $oss->up($res, $res, $this->mallId);
            if ($up) {
                if (file_exists($res)) @unlink($res);
            }
        }
        return [HTTP_SUCCESS, $up];
    }

}
